#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import webapp2
import cgi 
from Markov import Markov
import urllib 
from com.webapps.reddit.SubredditCloud import SubredditCloud
from com.webapps.politics.Insult import Insult

class MainHandler(webapp2.RequestHandler):
    def get(self):
        htmlFile = open("Homepage.html")
        htmlString = htmlFile.read()
        self.response.write(htmlString)
        

class RandomTextGen(webapp2.RequestHandler):
    def post(self):
        inputFilename = self.request.get('input')
        if inputFilename is not None and  inputFilename != "":
            contentfile = open('RandomTextTraining/'+ inputFilename +'.txt')
            contentString = contentfile.read()
            contentfile.close()
        else:
            contentString = urllib.unquote_plus(urllib.unquote(cgi.escape(self.request.get('myText'))))
         
        if contentString == '' or contentString is None or len(contentString.split()) < 50:
            outputString = 'Too small an output. A page of content would be nice'
        else: 
            markov = None
            markov = Markov('!@#' + contentString + '!@#')
            outputString = markov.generateText()
            del(markov)
        outputString = outputString.replace("\n",'<br>')
        htmlFile = open("RandomText.html")
        htmlString = htmlFile.read()
        htmlString = htmlString.replace('<!--addGenText-->',outputString)
        self.response.write(htmlString)
        htmlFile.close()
    
class RandomTextHome(webapp2.RequestHandler):
    def get(self):
        htmlFile = open("RandomText.html")
        htmlString = htmlFile.read()
        self.response.write(htmlString) 
        htmlFile.close()

class InsultGen(webapp2.RequestHandler):
    def get(self):
        clickSubmit = self.request.get('submitted')
        htmlFile = open("insult.html")
        htmlString = htmlFile.read()
        if clickSubmit == "Insult some more!":
            insult = Insult()
            insultString = insult.generate()
            htmlString = htmlString.replace('<!--addGenText-->',insultString)
        self.response.write(htmlString)
        htmlFile.close()
            

class RedditCloud(webapp2.RequestHandler):
    replacementString = '''<!-- "Hello", "world", "normally", "you", "want", "more", "words",
        "than", "this"-->'''
    errorString = '<!-- errors go here -->'
    def errorPrint(self,errorMsg):
        htmlFile = open("wordcloud.html")
        htmlString = htmlFile.read()
        htmlString = htmlString.replace(self.errorString,errorMsg)
        self.response.write(htmlString) 
        htmlFile.close()
        
        
    def get(self):
        subredditName = self.request.get('subreddit')
        cloudstring = None
        htmlString = None
        wordList = None
        htmlFile = None
        htmlString = None
        if subredditName == "" or subredditName is None:
            self.errorPrint("")
        else:
            stopwdfile = open("stopwords.txt")
            stopwdstring = stopwdfile.read()
            stopwdfile.close()
            subredditcloud = None
            subredditcloud = SubredditCloud(stopwdstring)
            wordList = subredditcloud.subredditSummary(subredditName)
            del subredditcloud
            if wordList == 'Can\'t access this subreddit for whatever reason' or wordList is None :
                self.errorPrint('Can\'t access this subreddit for whatever reason <br>')
            else: 
                cloudstring = ""
                for tup in wordList:
                    cloudstring = cloudstring + ',' +','.join(['"' + tup[0] + '"']*tup[1])
                del wordList
                htmlFile = open("wordcloud.html")
                htmlString = htmlFile.read()
                htmlString = htmlString.replace(self.replacementString,cloudstring[1:])
                del cloudstring
                self.response.write(htmlString) 
                del htmlString
                htmlFile.close()
                del htmlFile

 
index = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

textgen =  webapp2.WSGIApplication([
    ('/RandomTextHome', RandomTextHome),
     ('/RandomTextGenerator', RandomTextGen)
], debug=True)

redditcloud = webapp2.WSGIApplication([
    ('/Subredditcloud', RedditCloud)
], debug=True)

insult = webapp2.WSGIApplication([
    ('/rightwingInsulter', InsultGen)
], debug=True)


 
